<template>
  <div class="margin-container-list">
    <!-- tab区 -->
    <div class="tab-style-default">
      <el-tabs v-model="tabActive" @tab-click="doChangeTab">
        <el-tab-pane v-for="(item, key) in labels" :key="key" :label="item" :name="key"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 条件区 -->
    <div class="mar-b-20">
      <div class="inline-flex">
        <el-select v-model="textCol" style="width: 150px">
          <el-option label="采购退货申请单号" value="purchaseOrderNo"></el-option>
          <el-option label="关联采购申请号" value="relationPurchaseOrderNo"></el-option>
        </el-select>
        <el-input v-model="textValue" placeholder="请输入内容" style="width: 200px;"></el-input>
      </div>
      <el-select v-model="defaultQuery.supplierId" placeholder="供应商" clearable class="pad-l-10">
        <el-option label="不限" value="0"></el-option>
        <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
          :value="item.supplierId"></el-option>
      </el-select>
      <el-select v-model="defaultQuery.purchaseOrderStatus" v-if="purchaseOrderStatusList.length > 0" placeholder="状态"
        clearable class="pad-l-10" style="width: 140px">
        <el-option v-for="(item, index) in purchaseOrderStatusList" :key="index" :label="item.label"
          :value="item.value"></el-option>
      </el-select>
      <div class="inline-flex">
        <el-select v-model="dateTimeValue" class="pad-l-10" style="width: 120px">
          <el-option label="创建时间" value="createTime"></el-option>
          <el-option label="提交时间" value="submitTime"></el-option>
          <el-option label="审核时间" value="auditTime"></el-option>
          <el-option label="完成时间" value="completeTime"></el-option>
        </el-select>
        <el-date-picker v-model="dateTimePicker" type="datetimerange" range-separator="至"
          value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <el-button-group class="mar-l-20">
        <el-button type="primary" @click="doSearch">查询</el-button>
        <el-button plain @click="doResetSearch">重置</el-button>
      </el-button-group>
    </div>
    <!-- 按钮区 -->
    <div class="mar-b-20 btn-area" v-if="warehouseObj.warehouseSource === '1'">
      <el-button type="primary" v-if="tabActive == '0'" @click="doAddOrEdit">添加</el-button>
      <el-button type="primary" v-if="tabActive == '0'" @click="doBatchSubmitOrder">批量提交</el-button>
      <el-button type="primary" v-if="tabActive == '1'" @click="doBatchRevokeOrder">批量撤销提交</el-button>
      <el-button v-if="tabActive == '0'" @click="doBatchDeleteOrder">批量删除</el-button>
      <el-button @click="doExport">导出</el-button>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中">
        <el-table-column width="50px" type="selection"></el-table-column>
        <el-table-column label="采购退货申请单号" prop="purchaseOrderNo" align="center">
        </el-table-column>
        <el-table-column label="关联采购申请号" prop="relationPurchaseOrderNo" align="center">
        </el-table-column>
        <el-table-column label="供应商" prop="supplierName" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.supplierName ? scope.row.supplierName :'不限' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" label="商品总数量" prop="goodsNum" align="center">
        </el-table-column>
        <!-- 【出库中】【已完成】【全部】下显示此列 -->
        <el-table-column v-if="tabActive == '2' || tabActive == '4' || tabActive == 'all'" width="220px" label="已出库数量" prop="warehouseOutNum"
          align="center">
          <!-- <template slot-scope="scope">
            <span>已入库：{{ scope.row.stockInNum }}</span>
            <br />
            <span class="font-red" v-if="scope.row.stockOutNum > 0">已退货：{{ scope.row.stockOutNum }}</span>
          </template> -->
        </el-table-column>
        <el-table-column width="200px" label="创建时间" prop="createTime" align="center">
        </el-table-column>
        <!-- 【出库中】【已完成】【全部】下显示此列 -->
        <el-table-column v-if="tabActive == '2' || tabActive == '4' || tabActive == 'all'" width="220px" label="状态"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.purchaseOrderStatus === 2">待出库</span>
            <span v-else-if="scope.row.purchaseOrderStatus === 3">部分出库</span>
            <span v-else>{{ dict.purchaseOrderStatus[scope.row.purchaseOrderStatus] }}</span>
          </template>
        </el-table-column>
        <!-- 【审核未通过】下显示此列 -->
        <el-table-column v-if="tabActive == '-1'" width="220px" label="审核意见" prop="auditRemark" align="center">
          <template slot-scope="scope">
            <el-popover placement="top" width="200" trigger="click" :content="scope.row.auditRemark">
              <el-button type="text" slot="reference">点击查看</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="300px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 0"
              @click="doAddOrEdit(scope.row)">编辑
            </el-button>
            <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 0"
              @click="doBatchSubmitOrder(scope.row)">提交</el-button>
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 1"
              @click="doBatchRevokeOrder(scope.row)">撤销提交</el-button>
            <el-button type="text" size="medium"
              v-if="scope.row.notWarehouseOutNum > 0 && scope.row.purchaseOrderStatus !== -2"
              @click="doStockInOrder(scope.row)">出库</el-button>
            <el-button type="text" size="medium" v-if="scope.row.warehouseOutNum > 0"
              @click="doStockInHistory(scope.row)">出库记录</el-button>
            <el-button type="text" size="medium" v-if="scope.row.purchaseOrderStatus == 0"
              @click="doBatchDeleteOrder(scope.row)">
              删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="searchListQuery.currentPage"
      :limit.sync="searchListQuery.size" @pagination="initList" />

    <!-- 采购退货订单dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="purchaseOrderVisible" width="580px">
      <purchase-order-form-page :showFlag="purchaseOrderVisible" :purchaseOrder="purchaseOrderForm"
        @callback="doCallbackPurchaseOrder"></purchase-order-form-page>
    </el-dialog>

    <!-- 入库单dialog -->
    <el-dialog title="新增出库单" :visible.sync='stockVisible' width="580px">
      <warehouse-stock-edit :showFlag="stockVisible" :businessTypeList="['6']" :stockOrder="stockForm"
        @callback="doCloseStockOrder"></warehouse-stock-edit>
    </el-dialog>

    <!-- 采购退货申请单dialog -->
    <!--    <el-dialog title="采购退货申请" :visible.sync='refundGoodsVisible' width="580px">
      <warehouse-refund-goods-edit :showFlag="refundGoodsVisible" :businessTypeList="['1']" :purchaseOrder="stockForm"
        @callback="doCloseRefundGoodsOrder"></warehouse-refund-goods-edit>
    </el-dialog> -->
    <WarehouseRefundGoodsEdit ref="warehouseRefundGoodsEditRef" :onSuccessCall="onSuccessCall">
    </WarehouseRefundGoodsEdit>
  </div>
</template>

<script>
  import warehouseStockEdit from '@/views/warehouse/components/warehouse-stock-edit'
  import purchaseOrderFormPage from '@/views/warehouse/components/purchase-order-form-page'
  import WarehouseRefundGoodsEdit from '@/views/warehouse/components/warehouse-refund-goods-edit'
  import {
    getWarehouse
  } from '@/api/warehouse/warehouseInfo'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    pagingPurchaseOrder,
    statPurchaseOrder,
    doExportByWarehouse,
    batchSubmit,
    batchRevoke,
    batchDelete
  } from '@/api/warehouse/purchaseOrder'

  export default {
    components: {
      purchaseOrderFormPage,
      warehouseStockEdit,
      WarehouseRefundGoodsEdit
    },
    data() {
      return {
        // tab选中对象
        tabActive: '0',
        // tab标签
        labels: {
          '0': '待提交(0)',
          '1': '待审核(0)',
          '2': '出库中(0)',
          '4': '已完成(0)',
          '-1': '审核未通过(0)',
          'all': '全部退货申请(0)'
        },
        // tab标签模板
        labelTemp: {
          '0': '待提交(s)',
          '1': '待审核(s)',
          '2': '出库中(s)',
          '4': '已完成(s)',
          '-1': '审核未通过(s)',
          'all': '全部退货申请(s)'
        },
        // 数据字典
        dict: {
          invoiceType: {},
          purchaseOrderStatus: {}
        },
        // 文本model
        textCol: 'purchaseOrderNo',
        textValue: '',
        // 日期model
        dateTimeValue: 'createTime',
        dateTimePicker: [],
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          warehouseId: '',
          currentPage: 1,
          size: 10,
          supplierId: '',
          purchaseOrderStatus: ''
        },
        // 查询条件
        searchListQuery: {},
        // 采购退货单状态集合
        purchaseOrderStatusList: [],
        // 供应商集合
        supplierList: [],
        // 仓库对象
        warehouseObj: {
          warehouseSource: ''
        },
        // 采购退货订单表单
        purchaseOrderForm: {
          purchaseOrderId: '',
          supplierId: '',
          consigneeProvinceCode: '',
          consigneeCityCode: '',
          consigneeDistrictCode: '',
          consigneeAddress: '',
          consignee: '',
          consigneePhone: '',
          remark: ''
        },
        // 出入库单对象
        stockForm: {
          enterpriseId: '',
          warehouseId: '',
          supplierId: '',
          businessType: '6',
          stockSource: '1',
          stockSourceNo: '',
          disableSelectSupplier: '',
          isEditRefundOrder: ''
        },
        dialogTitle: '',
        // 采购退货单visible
        purchaseOrderVisible: false,
        // 出入库单visible
        stockVisible: false,
        // 勾选集合
        multipleSelection: [],
        total: 0,
        listLoading: false,
        dataList: []
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.purchaseOrderNo) {
        this.textCol = 'relationPurchaseOrderNo'
        this.textValue = queryParams.purchaseOrderNo
        this.tabActive = queryParams.tabActiveStatusName
      }
      const supplierForm = {
        enterpriseId: this.getEnterpriseId(),
        settlementType: 30
      }
      // 获取供应商列表
      listSupplier(supplierForm).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      // 获取仓库信息
      getWarehouse(this.getWarehouseId()).then((response) => {
        if (response.isError) return
        this.warehouseObj = response.data
      })
      this.initList()
    },
    methods: {
      // tab切换事件
      doChangeTab() {
        var list = []
        if (this.tabActive === '2' || this.tabActive === '4' || this.tabActive === 'all') {
          for (var key in this.dict.purchaseOrderStatus) {
            if (this.dict.purchaseOrderStatus[key] === '待入库') {
              this.dict.purchaseOrderStatus[key] = '待出库'
            }
            if (this.dict.purchaseOrderStatus[key] === '部分入库') {
              this.dict.purchaseOrderStatus[key] = '部分出库'
            }
            list.push({
              label: this.dict.purchaseOrderStatus[key],
              value: key
            })
          }
          // 显示状态【已完成】【已终止】
          if (this.tabActive === '2') {
            list = list.filter(item => item.value === '2' || item.value === '3')
          }
          // 显示状态【已完成】【已终止】
          if (this.tabActive === '4') {
            list = list.filter(item => item.value === '4' || item.value === '-2')
          }
        }
        this.purchaseOrderStatusList = list
        this.doResetSearch()
      },
      initList() {
        this.setQueryCondition()
        this.listLoading = true
        this.stat()
        pagingPurchaseOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          this.dataList = response.data.records
          this.total = response.data.total
          this.dict = response.data.dict
        })
      },
      // 设置查询条件
      setQueryCondition() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.dateTimeValue
        this.searchListQuery.startDate = (this.dateTimePicker && this.dateTimePicker.length > 0) ? this.dateTimePicker[
          0] : ''
        this.searchListQuery.endDate = (this.dateTimePicker && this.dateTimePicker.length > 1) ? this.dateTimePicker[
          1] : ''
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.warehouseId = this.getWarehouseId()
        this.searchListQuery.purchaseOrderType = 2
        if (!this.searchListQuery.purchaseOrderStatus) {
          let tabStatus = ''
          switch (this.tabActive) {
            case '0':
            case '1':
            case '-1':
              tabStatus = this.tabActive
              break
            case '2':
            case '4':
            case 'all':
              tabStatus = this.purchaseOrderStatusList.map(item => item.value).join(',')
              break
            default:
          }
          this.searchListQuery.purchaseOrderStatusList = tabStatus
        }
      },
      // 统计
      stat() {
        statPurchaseOrder({
          warehouseId: this.getWarehouseId(),
          purchaseOrderType: 2
        }).then(response => {
          if (response.isError) return
          this.labels[0] = this.labelTemp[0].replace('s', response.data[0])
          this.labels[1] = this.labelTemp[1].replace('s', response.data[1])
          this.labels[2] = this.labelTemp[2].replace('s', response.data[2] + response.data[3])
          this.labels[4] = this.labelTemp[4].replace('s', response.data[4] + response.data[-2])
          this.labels[-1] = this.labelTemp[-1].replace('s', response.data[-1])
          this.labels['all'] = this.labelTemp['all'].replace('s', response.data['all'])
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.dateTimeValue = originData.dateTimeValue
        this.dateTimePicker = originData.dateTimePicker
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 导出事件
      doExport() {
        if (this.dataList.length === 0) {
          this.$message({
            type: 'error',
            message: '暂无可导出数据'
          })
          return
        }
        let form = {
          enterpriseId: this.getEnterpriseId()
        }
        this.setQueryCondition()
        if (this.multipleSelection.length > 0) {
          const purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
          form.purchaseOrderIds = purchaseOrderIds.join(',')
          form.purchaseOrderStatusList = this.searchListQuery.purchaseOrderStatusList
        } else {
          form = this.searchListQuery
        }
        window.open(doExportByWarehouse(form), '_blank')
      },
      // 关闭采购退货单dialog事件
      doCallbackPurchaseOrder(refresh) {
        if (refresh) {
          this.initList()
        }
        this.purchaseOrderVisible = false
      },
      // 添加或编辑
      doAddOrEdit(row) {
        if (row) {
          this.purchaseOrderForm.purchaseOrderId = row.purchaseOrderId
        } else {
          this.purchaseOrderForm.purchaseOrderId = ''
        }
        this.$refs.warehouseRefundGoodsEditRef.open(this.purchaseOrderForm)
      },
      // 查看详情
      doLinkDetail(row) {
        this.$router.push({
          path: '/warehouse/warehouse-refund-goods/detail/index',
          query: {
            purchaseOrderId: row.purchaseOrderId
          }
        })
      },
      // 批量提交事件
      doBatchSubmitOrder(row) {
        var purchaseOrderIds = []
        if (row && row.purchaseOrderId) {
          purchaseOrderIds.push(row.purchaseOrderId)
        } else {
          if (this.multipleSelection.length > 0) {
            purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
          }
        }
        if (purchaseOrderIds.length <= 0) {
          this.$message({
            type: 'error',
            message: '请选择采购退货单'
          })
          return
        }
        this.listLoading = true
        batchSubmit(purchaseOrderIds).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          const data = response.data
          var msg = '提交成功'
          if (purchaseOrderIds.length > 1) {
            msg = '共提交' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
          } else {
            if (data.failure > 0) {
              msg = '提交失败'
            }
          }
          this.$message({
            type: 'success',
            message: msg
          })
          this.initList()
        })
      },
      // 批量撤销提交事件
      doBatchRevokeOrder(row) {
        var purchaseOrderIds = []
        if (row && row.purchaseOrderId) {
          purchaseOrderIds.push(row.purchaseOrderId)
        } else {
          if (this.multipleSelection.length > 0) {
            purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
          }
        }
        if (purchaseOrderIds.length <= 0) {
          this.$message({
            type: 'error',
            message: '请选择采购退货单'
          })
          return
        }
        this.listLoading = true
        batchRevoke(purchaseOrderIds).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          const data = response.data
          var msg = '撤销成功'
          if (purchaseOrderIds.length > 1) {
            msg = '共撤销提交' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
          } else {
            if (data.failure > 0) {
              msg = '撤销失败'
            }
          }
          this.$message({
            type: 'success',
            message: msg
          })
          this.initList()
        })
      },
      // 出库事件
      doStockInOrder(row) {
        this.stockForm = {
          enterpriseId: row.enterpriseId,
          warehouseId: row.warehouseId,
          supplierId: row.supplierId,
          businessType: '6',
          stockSource: '1',
          stockSourceNo: row.purchaseOrderNo,
          disableSelectSupplier: true,
          purchaseOrderId: row.purchaseOrderId
        }
        this.stockVisible = true
      },
      // 关闭出入库单dialog事件
      doCloseStockOrder() {
        this.stockVisible = false
      },
      // 入库记录事件
      doStockInHistory(row) {
        this.$router.push({
          path: '/stock/warehouse-stock/index',
          query: {
            purchaseOrderNo: row.purchaseOrderNo,
            tabActiveStatusName: 'all'
          }
        })
      },
      // 批量删除事件
      doBatchDeleteOrder(row) {
        var purchaseOrderIds = []
        if (row && row.purchaseOrderId) {
          purchaseOrderIds.push(row.purchaseOrderId)
        } else {
          if (this.multipleSelection.length > 0) {
            purchaseOrderIds = this.multipleSelection.map(item => item.purchaseOrderId)
          }
        }
        if (purchaseOrderIds.length <= 0) {
          this.$message({
            type: 'error',
            message: '请选择采购退货单'
          })
          return
        }
        this.listLoading = true
        batchDelete(purchaseOrderIds).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          const data = response.data
          var msg = '删除成功'
          if (purchaseOrderIds.length > 1) {
            msg = '共删除' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
          } else {
            if (data.failure > 0) {
              msg = '删除失败'
            }
          }
          this.$message({
            type: 'success',
            message: msg
          })
          this.initList()
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      onSuccessCall() {
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .btn-area {
    button {
      min-width: 90px;
    }
  }
</style>
